<?php
namespace submodule\controllers;

use Yii;
//use backend\modules\mobo\models\BackendMenu;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

use submodule\models\Module;
use submodule\models\Models;
use submodule\models\ModelsField;
use common\components\Tree;
use base\YiiMobo;

use \common\models\DIYModel;

class ModuleController extends \submodule\base\BaseModelsController
{

	
	public $tablename = 'submodule_module';
	
	public $submodel;

	
	
	
	
	public function init(){
		
		parent::init();
		$this->submodel =  (object)null;
		
		$this->submodel->controllerUrl = [
		    'index'=> $this->module->id.'/index/index',
			'create' => $this->module->id.'/index/create',
			'update'=> $this->module->id.'/index/update',
			'batch'=> $this->module->id.'/index/batch',
			'view'=> $this->module->id.'/index/view',
			'delete'=> $this->module->id.'/index/delete',
			'status'=> $this->module->id.'/index/status',
			'linkage'=> $this->module->id.'/index/linkage',
		];
				//视图
		$this->submodel->viewFiles = [
		    'index'=> @$this->submodel->models['models']['setting']['index']['views'],
		    'form'=> @$this->submodel->models['models']['setting']['index']['views'],
			

		];
		
		$this->submodel->default_field = [];
		
		
		
	}

	/**
	 * 获取action的url
	 */
    public function getSubmodelActionUrl($action, $returnUrl = true){
		$url = isset($this->submodel->controllerUrl[$action[0]]) ? $this->submodel->controllerUrl[$action[0]] : false;
		$url = str_replace($action[0] , $url, $action);
		if ($returnUrl){
			$url = $this->createUrl($url);
		}
		return $url;
		
	}
	/**
	 * 设置视图文件
	 */
    public function setViewFiles($views){
		foreach($views as $k=>$view){
		    $this->submodel->viewFiles[$k]  = $view;
		}
	}
	
	/**
	 * 获取视图文件
	 */
    public function getViewFiles($action = 'index'){
		$viewfile = isset($this->submodel->viewFiles[$action]) ? $this->submodel->viewFiles[$action] : false;
		if (!$viewfile){
			$viewfile = "@submodule/views/submodel/submodel_".$action;
		}
		return $viewfile;
		
	}

	
	/**
	 * @return array action filters
	 */
	public function filters() {
     return array( 
        array('auth.filters.AuthFilter'),
            );
        }

    public function actionIndex()
	{
		$dirs_arr = [];
		$dirs = glob('modules'.DIRECTORY_SEPARATOR.'*');
		foreach ($dirs as $d) {
			if (is_dir($d)) {
				$d = basename($d);
				$dirs_arr[] = $d;
			}
		}
		
		define('INSTALL', true);

		$sql = 'select * from '.$this->tablename;
        $modules = [];
		$data = Yii::$app->db->createCommand($sql)->queryAll();
		foreach($data as $v){
			$modules[$v['module']] = $v;
		}
		//print_r($modules);
		echo $this->render('index', [
		    'dirs'=> $dirs_arr,
			'modules'=> $modules
		]);
	}
	
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionCreate($parentid = 0)
	{
		//print_r($this->fields);exit;
		$sql='select * from '.$this->tablename.' where id=0';
	
		$model = Yii::$app->getDb()->getTableSchema($this->tablename);
		$model =  (object)null;
		foreach (Yii::$app->getDb()->getTableSchema($this->tablename)->columns as $column) {
            $value = $column->defaultValue ? $column->defaultValue : '';
            $model->{$column->name} = $value;
			$model->attributes[$column->name] = $value;
            
        }
		
		if($this->models['models']['type'] == 'content'){
			foreach (Yii::$app->getDb()->getTableSchema($this->data_tablename)->columns as $column) {
				$value = $column->defaultValue ? $column->defaultValue : '';
				$model->{$column->name} = $value;
				$model->attributes[$column->name] = $value;
				
			}
		}else if($this->models['models']['type'] == 'category'){
			$model->parentid = $model->attributes['parentid'] = $parentid;
		}
        if(isset($_POST['Models']))
		{
			$this->submodelSaveForm();
		}
		$this->data['id'] = '';
		foreach($this->fields as $k=>$v){
		    $this->data[$v['field']] = isset($setting['defaultvalue']) ? $setting['defaultvalue'] : '';
		}
		//print_r($this->data);exit;
		return $this->render('modelsform_form',[
		    'model'=> $model,
		    'models'=> $this->models,
		    'headerPlugins'=> $this->headerPlugins(),
			'modelid' => $this->modelid,
			'formFields' => $this->formFields(),
			'fields' => $this->fields,
			'allowinput_fields'=> $this->allowinput_fields
		]);
	}
	
	
	/**
	 * 安装模块.
     * 
	 */
	public function actionInstall($module, $name){
		//写入module模型表
		$models = [];
		$model = new Models;
		$attributes = [
			'isdefault'=> -1,
			'name'=> $name,
			'tablename'=> $module,
			'type'=> $module,
		];
		$model->isNewRecord = true;
		$model->setAttributes($attributes);
		$model->save();
		$models[] = $model;
		$modelid = $model->modelid;
		$model = new Models;
		$attributes['isdefault'] = 1;
		$model->isNewRecord = true;
		$model->setAttributes($attributes);
		
		if($model->save()){
			$models[] = $model;
			//写入module模块表
			$modelModule = new Module;
			$attributes = [
				'module'=> $module,
				'name'=> $name,
				'tablename'=> $module,
				'path'=> $module,
				'version'=> '',
				'description'=> '',
				'setting'=>'',
				'addtime'=> time(),
				'modelid'=> $modelid
			];
			$modelModule->isNewRecord = true;
			$modelModule->setAttributes($attributes);
			if($modelModule->save()){
				$modelids = $this->install($models, $module);
				$this->actionUpdateCache($modelids);
				$this->OperTips($this->createUrl([$model->type.'/models/update', 'modelid'=>$model->modelid]));
			}
		}
		
		
	}
	

	/**
	 * 卸载模块.
     * 待完成
	 */
	public function actionUnstall(){
		
		
		
	}
	
	public function submodelSaveCallback($id, $data){
		Yii::$app->db->createCommand()->update($this->tablename, ['setting' =>json_encode($data[1], JSON_UNESCAPED_UNICODE)], 'modelid = '.$this->submodel->modelid)->execute();
		$this->actionCache($this->submodel->module);
		$this->OperTips(['backurl'=>$this->createUrl(['module/index'])]);
		
	}
	
		/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionConfig($modelid = 0)
	{

		$sql='select `module`,`setting` from '.$this->tablename.' where modelid = '.$modelid;
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		$this->submodel->module = $data['module'];
		$data['setting'] = $data['setting'] ? json_decode($data['setting'], true) : [];
		$model =  (object)null;
		$data['setting']['id'] = 1;

		$model->attributes = $data['setting'];
		
		$this->submodel->modelid = $modelid;
        $this->submodel->models = Yii::$app->FileCache->get('submodule_model_'.$this->submodel->modelid);
		//print_r($this->submodel->models);exit;
		$this->submodel->allowinput_fields = $this->submodel->models['allowinput_fields'];
		$this->submodel->fields = $this->submodel->models['fields'];
		$this->submodel->primarykey =  $this->submodel->models['primarykey'];
		$this->submodel->tablename = '{{%'.$this->submodel->models['models']['tablename'].'}}';
		$this->submodel->data_tablename = false;
		
        if(isset($_POST['Models']))
		{
			$this->submodelSaveForm();
		}

		return $this->render('config', [
		    'model'=> $model,
			'modelid'=> $modelid,
			'module'=> $this->submodel->module

		]);
	}
	
	public function actionDisabled($module, $disabled = 1){
		Yii::$app->db->createCommand()->update($this->tablename, ['disabled'=> $disabled], "module = '$module'")->execute();
		$this->OperTips();
	}
	/**
	 * 更新缓存
	 */
	public function actionCache($module, $goback = false){
		$sql="select * from {$this->tablename} where `module` = '$module'";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		$data['setting'] = $data['setting'] ? json_decode($data['setting'], true) : [];
		Yii::$app->FileCache->set("module_".$module, $data);
		
		$model_tablename = Models::tableName();
		$sql="select modelid from {$model_tablename} where `type` = '$module'";
		$data = Yii::$app->db->createCommand($sql)->queryColumn();
		$this->actionUpdateCache(array_values($data));
		if ($goback){
			$this->OperTips(['backurl'=>$this->createUrl(['module/index'])]);
		}
		
	}
	

}
